package ch.zbw.swt.sysventory.network.scan;

import java.util.ArrayList;
import java.util.List;

import ch.zbw.swt.sysventory.hibernate.entity.Computer;
import ch.zbw.swt.sysventory.hibernate.entity.Printer;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class ScanPrinter {

	private String namePrinter;
	private String driverNamePrinter;
	private String driverVersionPrinter;
	private Computer computer;

	private List<Printer> printers;

	// Constructor
	public ScanPrinter(Computer computer) {
		this.computer = computer;
		this.printers = new ArrayList<Printer>();

	}

	public List<Printer> getPrinter(String host) {

		List<String> pPrinter = new ArrayList<String>();
		List<String> pDriver = new ArrayList<String>();

		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM Win32_Printer";

		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// The Result is a Collection
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();

				String namePrinter = Dispatch.call(item, "Name").toString();
				String DriverNamePrinter = Dispatch.call(item, "DriverName")
						.toString();

				pPrinter.add(namePrinter);
				pPrinter.add(DriverNamePrinter);
			}

			query = "SELECT * FROM Win32_PrinterConfiguration";
			vCollection = axWMI.invoke("ExecQuery", new Variant(query));
			enumVariant = new EnumVariant(vCollection.toDispatch());
			item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();

				String DriverVersionPrinter = Dispatch.call(item,
						"DriverVersion").toString();
				String DriverCaptionPrinter = Dispatch.call(item, "Caption")
						.toString();

				pDriver.add(DriverCaptionPrinter);
				pDriver.add(DriverVersionPrinter);
			}

			for (int i = 0; i < pPrinter.size(); i = i + 2) {
				namePrinter = pPrinter.get(i);
				driverNamePrinter = pPrinter.get(i + 1);
				driverVersionPrinter = pDriver.get(i + 1);

				Printer printer = new Printer(namePrinter, driverNamePrinter,
						driverVersionPrinter, computer);

				printers.add(printer);
			}
		} catch (Exception e) {

		}

		return printers;

	}
}
